import React, { useState } from 'react';
import { Button } from 'antd';
import { 
  ReloadOutlined, 
  HomeOutlined, 
  LeftOutlined, 
  SettingOutlined, 
  UserOutlined, 
  GlobalOutlined, 
  CustomerServiceOutlined, 
  InfoCircleOutlined,
  ShoppingOutlined,
  ShoppingCartOutlined,
  InboxOutlined,
  WalletOutlined,
  ProfileOutlined,
  ToolOutlined,
  FileTextOutlined,
  TagsOutlined,
  TeamOutlined,
  SolutionOutlined,
  BankOutlined,
  DollarOutlined,
  CloseOutlined
} from '@ant-design/icons';
import SalesOrder from '../SalesOrder';
import SalesOrderReport from '../SalesOrderReport';
import './styles.scss';

// 二级菜单项组件
interface SubMenuItem {
  label: string;
  isReport?: boolean;
  separator?: boolean;
  reportPath?: string;
}

interface SubMenuGroup {
  title: string;
  items: SubMenuItem[];
}

interface NavTab {
  id: string;
  title: string;
  parentTitle: string;
  content?: React.ReactNode;
}

interface SubMenuProps {
  groups: SubMenuGroup[];
  isDataMenu?: boolean;
  onItemClick?: (parentTitle: string, item: SubMenuItem) => void;
  onReportClick?: (parentTitle: string, item: SubMenuItem) => void;
}

// 二级菜单组件
const SubMenu: React.FC<SubMenuProps> = ({ groups, isDataMenu, onItemClick, onReportClick }) => {
  const handleReportClick = (e: React.MouseEvent, parentTitle: string, item: SubMenuItem) => {
    e.stopPropagation();
    onReportClick?.(parentTitle, item);
  };

  return (
    <div className={`submenu ${isDataMenu ? 'data-submenu' : ''}`}>
      <div className={`submenu-content ${isDataMenu ? 'double-column' : ''}`}>
        {groups.map((group, groupIndex) => (
          <div key={groupIndex} className="submenu-group">
            <div className="submenu-title">{group.title}</div>
            <div className="submenu-items">
              {group.items.map((item, itemIndex) => (
                <div
                  key={itemIndex}
                  className="submenu-item"
                  data-separator={item.separator}
                  onClick={() => onItemClick?.(group.title, item)}
                >
                  <span>{item.label}</span>
                  {item.isReport && (
                    <span 
                      className="report-tag"
                      onClick={(e) => handleReportClick(e, group.title, item)}
                    >
                      报表
                    </span>
                  )}
                </div>
              ))}
            </div>
          </div>
        ))}
      </div>
    </div>
  );
};

// 菜单项组件
interface MenuItemProps {
  icon: React.ReactNode;
  label: string;
  active?: boolean;
  subMenuGroups?: SubMenuGroup[];
  isDataMenu?: boolean;
  onMenuItemClick?: (parentTitle: string, item: SubMenuItem) => void;
  onReportClick?: (parentTitle: string, item: SubMenuItem) => void;
}

const MenuItem: React.FC<MenuItemProps> = ({ 
  icon, 
  label, 
  active, 
  subMenuGroups, 
  isDataMenu,
  onMenuItemClick,
  onReportClick
}) => {
  const [showSubmenu, setShowSubmenu] = useState(false);
  
  return (
    <div
      className={`menu-item ${active ? 'active' : ''}`}
      onMouseEnter={() => setShowSubmenu(true)}
      onMouseLeave={() => setShowSubmenu(false)}
    >
      {icon}
      <span>{label}</span>
      {showSubmenu && subMenuGroups && (
        <SubMenu 
          groups={subMenuGroups} 
          isDataMenu={isDataMenu}
          onItemClick={onMenuItemClick}
          onReportClick={onReportClick}
        />
      )}
    </div>
  );
};

// 功能卡片组件
const FunctionCard = ({ icon, label, color }: { icon: React.ReactNode, label: string, color: string }) => (
  <div className="function-card">
    <div className="icon-wrapper" style={{ backgroundColor: color }}>
      {icon}
    </div>
    <div className="label">{label}</div>
  </div>
);

// 常用功能项组件
const CommonFunctionItem = ({ label, icon }: { label: string, icon?: React.ReactNode }) => (
  <div className="common-function-item">
    {icon && <span className="item-icon">{icon}</span>}
    {label}
  </div>
);

// 侧边卡片组件
const SideCard = ({ title, children, icon }: { title: string, children: React.ReactNode, icon?: React.ReactNode }) => (
  <div className="side-card">
    <div className="side-card-header">
      <span>{title}</span>
      {icon && <div className="icon">{icon}</div>}
    </div>
    <div className="side-card-content">
      {children}
    </div>
  </div>
);

const Home: React.FC = () => {
  const [activeTabs, setActiveTabs] = useState<NavTab[]>([]);
  const [activeTabId, setActiveTabId] = useState<string | null>(null);

  // 销售菜单的二级菜单数据
  const salesSubMenuGroups: SubMenuGroup[] = [
    {
      title: "销售",
      items: [
        { label: "销售预定", isReport: true },
        { label: "销售", isReport: true },
        { label: "销售退货", isReport: true }
      ]
    },
    {
      title: "零售",
      items: [
        { label: "零售收银", isReport: true },
        { label: "零售退货", isReport: true },
        { label: "积分兑换商品", isReport: true },
        { label: "客户储值", isReport: true }
      ]
    }
  ];

  // 进货菜单的二级菜单数据
  const purchaseSubMenuGroups: SubMenuGroup[] = [
    {
      title: "进货",
      items: [
        { label: "进货预定", isReport: true },
        { label: "进货", isReport: true },
        { label: "进货退货", isReport: true }
      ]
    }
  ];

  // 库存菜单的二级菜单数据
  const inventorySubMenuGroups: SubMenuGroup[] = [
    {
      title: "库存",
      items: [
        { label: "调拨单", isReport: true },
        { label: "库存盘点", isReport: true },
        { label: "组装拆卸", isReport: true },
        { label: "其他入库单", isReport: true },
        { label: "其他出库单", isReport: true }
      ]
    }
  ];

  // 财务菜单的二级菜单数据
  const financeSubMenuGroups: SubMenuGroup[] = [
    {
      title: "财务",
      items: [
        { label: "往来账", isReport: true },
        { label: "应收欠款", isReport: true },
        { label: "收款单", isReport: true },
        { label: "应付欠款", isReport: true },
        { label: "付款单", isReport: true },
        { label: "核销单", isReport: true }
      ]
    }
  ];

  // 资料菜单的二级菜单数据
  const dataSubMenuGroups: SubMenuGroup[] = [
    {
      title: "基础资料",
      items: [
        { label: "商品管理" },
        { label: "客户" },
        { label: "供应商" },
        { label: "仓库" },
        { label: "门店" }
      ]
    },
    {
      title: "辅助资料",
      items: [
        { label: "商品分类" },
        { label: "属性设置" },
        { label: "计量单位" },
        { label: "商品品牌", separator: true },
        { label: "客户等级价" },
        { label: "商品套餐" },
        { label: "条码打印" }
      ]
    }
  ];

  // 设置菜单的二级菜单数据
  const settingsSubMenuGroups: SubMenuGroup[] = [
    {
      title: "设置",
      items: [
        { label: "高级设置" },
        { label: "系统参数" },
        { label: "职员管理" },
        { label: "业务员管理" },
        { label: "权限设置" },
        { label: "数据授权" },
        { label: "打印模板" },
        { label: "字段设置" },
        { label: "单号规则" },
        { label: "操作日志" }
      ]
    }
  ];

  const handleMenuItemClick = (parentTitle: string, item: SubMenuItem) => {
    const tabId = `${parentTitle}-${item.label}`;
    
    // 如果标签已存在，只激活它
    if (activeTabs.some(tab => tab.id === tabId)) {
      setActiveTabId(tabId);
      return;
    }

    // 添加新标签
    const newTab: NavTab = {
      id: tabId,
      title: item.label,
      parentTitle,
      content: getTabContent(item.label)  // 根据标签获取对应的内容组件
    };

    setActiveTabs([...activeTabs, newTab]);
    setActiveTabId(tabId);
  };

  // 根据标签名获取对应的内容组件
  const getTabContent = (label: string) => {
    switch (label) {
      case '销售预定':
        return <SalesOrder />;
      case '销售预定报表':
        return <SalesOrderReport />;
      default:
        return <div>开发中...</div>;
    }
  };

  const handleReportClick = (parentTitle: string, item: SubMenuItem) => {
    // 处理报表点击事件
    const reportId = `${parentTitle}-${item.label}-报表`;
    
    // 如果报表标签已存在，只激活它
    if (activeTabs.some(tab => tab.id === reportId)) {
      setActiveTabId(reportId);
      return;
    }

    // 添加新的报表标签
    const newTab: NavTab = {
      id: reportId,
      title: `${item.label}报表`,
      parentTitle,
      content: getTabContent(`${item.label}报表`)  // 添加这一行，提供报表内容组件
    };

    setActiveTabs([...activeTabs, newTab]);
    setActiveTabId(reportId);
  };

  const handleCloseTab = (tabId: string, event: React.MouseEvent) => {
    event.stopPropagation();
    const newTabs = activeTabs.filter(tab => tab.id !== tabId);
    setActiveTabs(newTabs);

    // 如果关闭的是当前激活的标签，激活最后一个标签
    if (tabId === activeTabId && newTabs.length > 0) {
      setActiveTabId(newTabs[newTabs.length - 1].id);
    }
  };

  return (
    <div className="home-container">
      {/* 左侧菜单 */}
      <div className="sidebar">
        <div className="logo">
          <img src="/logo.png" alt="企云乐" />
          <span>企云乐</span>
          <div className="erp-tag">云ERP</div>
        </div>
        <div className="menu">
          <MenuItem 
            icon={<ShoppingOutlined className="menu-icon-ant" />} 
            label="销售" 
            active={true} 
            subMenuGroups={salesSubMenuGroups}
            onMenuItemClick={handleMenuItemClick}
            onReportClick={handleReportClick}
          />
          <MenuItem 
            icon={<ShoppingCartOutlined className="menu-icon-ant" />} 
            label="进货" 
            subMenuGroups={purchaseSubMenuGroups}
            onMenuItemClick={handleMenuItemClick}
            onReportClick={handleReportClick}
          />
          <MenuItem 
            icon={<InboxOutlined className="menu-icon-ant" />} 
            label="库存" 
            subMenuGroups={inventorySubMenuGroups}
            onMenuItemClick={handleMenuItemClick}
            onReportClick={handleReportClick}
          />
          <MenuItem 
            icon={<WalletOutlined className="menu-icon-ant" />} 
            label="财务" 
            subMenuGroups={financeSubMenuGroups}
            onMenuItemClick={handleMenuItemClick}
            onReportClick={handleReportClick}
          />
          <MenuItem 
            icon={<ProfileOutlined className="menu-icon-ant" />} 
            label="资料" 
            subMenuGroups={dataSubMenuGroups}
            isDataMenu={true}
            onMenuItemClick={handleMenuItemClick}
            onReportClick={handleReportClick}
          />
          <MenuItem 
            icon={<ToolOutlined className="menu-icon-ant" />} 
            label="设置"
            subMenuGroups={settingsSubMenuGroups}
            onMenuItemClick={handleMenuItemClick}
            onReportClick={handleReportClick}
          />
        </div>
      </div>

      {/* 主内容区 */}
      <div className="main-content">
        {/* 顶部导航 */}
        <div className="top-nav">
          <div className="nav-header">
            <div className="left-controls">
              <span className="company-name">喵喵喵进销存</span>
              <div className="breadcrumb-divider"></div>
              <div className="breadcrumb">
                {activeTabId && activeTabs.find(tab => tab.id === activeTabId) && (
                  <>
                    <span className="parent-title">{activeTabs.find(tab => tab.id === activeTabId)?.parentTitle}</span>
                    <span className="separator">/</span>
                    <span className="current-title">{activeTabs.find(tab => tab.id === activeTabId)?.title}</span>
                  </>
                )}
              </div>
            </div>
            <div className="right-controls">
              <Button type="text" icon={<SettingOutlined />}>设置门店</Button>
              <div className="divider"></div>
              <Button type="text" icon={<UserOutlined />}>修改密码</Button>
              <Button type="text" icon={<GlobalOutlined />}>中文</Button>
              <Button type="text" icon={<CustomerServiceOutlined />}>在线客服</Button>
            </div>
          </div>
          <div className="nav-tabs">
            {activeTabs.map(tab => (
              <div
                key={tab.id}
                className={`nav-tab ${activeTabId === tab.id ? 'active' : ''}`}
                onClick={() => setActiveTabId(tab.id)}
              >
                {/* 添加图标 - 根据父级菜单类型 */}
                {tab.parentTitle === "销售" && <ShoppingOutlined className="tab-icon" />}
                {tab.parentTitle === "进货" && <ShoppingCartOutlined className="tab-icon" />}
                {tab.parentTitle === "库存" && <InboxOutlined className="tab-icon" />}
                {tab.parentTitle === "财务" && <WalletOutlined className="tab-icon" />}
                {tab.parentTitle === "资料" && <ProfileOutlined className="tab-icon" />}
                {tab.parentTitle === "设置" && <ToolOutlined className="tab-icon" />}
                
                <span className="tab-title">{tab.title}</span>
                <CloseOutlined
                  className="close-icon"
                  onClick={(e) => handleCloseTab(tab.id, e)}
                />
              </div>
            ))}
          </div>
        </div>

        {/* 内容区域 */}
        <div className="content-area">
          {activeTabId ? (
            // 显示当前激活的标签页内容
            activeTabs.find(tab => tab.id === activeTabId)?.content
          ) : (
            <>
              <div className="content-header">
                <div className="nav-buttons">
                  <LeftOutlined />
                  <HomeOutlined />
                </div>
              </div>

              {/* 功能卡片区域 */}
              <div className="function-cards">
                <div className="function-row">
                  <FunctionCard
                    icon={<FileTextOutlined className="card-icon-ant" />}
                    label="销售"
                    color="#4cd174"
                  />
                  <FunctionCard
                    icon={<ShoppingCartOutlined className="card-icon-ant" />}
                    label="进货"
                    color="#4cd174"
                  />
                  <FunctionCard
                    icon={<TagsOutlined className="card-icon-ant" />}
                    label="商品"
                    color="#3296fa"
                  />
                  <FunctionCard
                    icon={<TeamOutlined className="card-icon-ant" />}
                    label="客户"
                    color="#3296fa"
                  />
                </div>
                <div className="function-row-bottom">
                  <FunctionCard
                    icon={<SolutionOutlined className="card-icon-ant" />}
                    label="供应商"
                    color="#3296fa"
                  />
                  <FunctionCard
                    icon={<BankOutlined className="card-icon-ant" />}
                    label="应收欠款"
                    color="#f7b84f"
                  />
                  <FunctionCard
                    icon={<DollarOutlined className="card-icon-ant" />}
                    label="应付欠款"
                    color="#f7b84f"
                  />
                  <div className="empty-card"></div>
                </div>
              </div>

              {/* 常用功能区域 */}
              <div className="common-functions">
                <div className="section-title">常用功能</div>
                <div className="function-items">
                  <CommonFunctionItem 
                    icon={<ShoppingCartOutlined />} 
                    label="进货单报表" 
                  />
                  <CommonFunctionItem 
                    icon={<FileTextOutlined />} 
                    label="销售单报表" 
                  />
                  <CommonFunctionItem 
                    icon={<TeamOutlined />} 
                    label="客户管理" 
                  />
                  <CommonFunctionItem 
                    icon={<TagsOutlined />} 
                    label="商品管理" 
                  />
                </div>
              </div>
            </>
          )}
        </div>
      </div>

      {/* 右侧边栏 - 只在没有激活标签时显示 */}
      {!activeTabId && (
        <div className="right-sidebar">
          <SideCard title="新手向导" icon={<InfoCircleOutlined />}>
            <div className="guide-content">
              <p>三个小步骤快速上手，轻轻效率提升30%</p>
              <Button type="primary" className="guide-button">即刻开始</Button>
            </div>
          </SideCard>

          <SideCard title="公告信息" icon={<InfoCircleOutlined />}>
            <div className="announcement-content">
              <p>可在系统设置里设置公告信息哦</p>
            </div>
          </SideCard>

          <SideCard title="多端操作">
            <div className="multi-device">
              <p>下载手机端，随时随地做生意。</p>
              <Button type="primary" className="download-button">手机版下载</Button>
              <p>您也可以下载我们的PC版本。</p>
              <div className="wechat-service">
                <span className="wechat-icon"></span>
                微信在线客服
              </div>
            </div>
          </SideCard>

          <SideCard title="打印助手">
            <div className="print-helper">
              <p>如有打印需求，请下载我们的打印助手。</p>
              <p>支持Windows7及以上版本。</p>
            </div>
          </SideCard>
        </div>
      )}
    </div>
  );
};

export default Home; 